package com.limh.readers.activity

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.os.Handler
import android.support.v4.widget.SwipeRefreshLayout
import android.view.MotionEvent
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import butterknife.BindView
import butterknife.OnClick
import com.limh.readers.R
import com.limh.readers.bean.Article
import com.limh.readers.bean.Magazine
import com.limh.readers.bean.Result
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import org.jsoup.Jsoup
import rx.Observable
import rx.schedulers.Schedulers

/**
 * Function:
 * author: limh
 * time:2017/7/29
 */
class WebInfoActivity : BaseActivity() {
    @BindView(R.id.txt_title)
    lateinit var txtTitle: TextView
    @BindView(R.id.refresh_web)
    lateinit var refreshWeb: SwipeRefreshLayout
    @BindView(R.id.web_info)
    lateinit var webInfo: WebView
    @BindView(R.id.txt_author)
    lateinit var txtAuthor: TextView
    @BindView(R.id.txt_size)
    lateinit var txtSize: TextView

    lateinit var link: String
    lateinit var table: String
    var id: Int = 0

    lateinit var dialog: ProgressDialog
    val TAG = "WebInfoActivity"
    var magazine: Magazine? = null
    var article: Article? = null

    var isSizeChange = false

    override fun findView() {
        setContentView(R.layout.activity_web)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initViews() {
        txtTitle.text = intent.getStringExtra("title")
        txtAuthor.text = intent.getStringExtra("author")
        link = intent.getStringExtra("artLink")
        table = intent.getStringExtra("table")
        id = intent.getIntExtra("id", 0)
        LogUtil.i(TAG, "url = " + link)
        val setting = webInfo.settings
        setting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        setting.loadWithOverviewMode = true
        setting.builtInZoomControls = true
        setting.displayZoomControls = false
        setting.loadsImagesAutomatically = true
        setting.defaultTextEncodingName = "utf-8"
        webInfo.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                return super.shouldOverrideUrlLoading(view, url)
            }
        }

        webInfo.setOnTouchListener({ _, event -> event.action == MotionEvent.ACTION_MOVE })
        refreshWeb.setOnRefreshListener {
            getArticle()
        }
    }

    override fun initDatas() {
        dialog = ProgressDialog(this)
        dialog.setMessage("加载中，请稍后...")
        dialog.show()
        getArticle()
    }

    @OnClick(R.id.image_close, R.id.txt_size)
    fun OnClick(view: View) {
        when (view.id) {
            R.id.image_close -> finish()
            R.id.txt_size -> {
                isSizeChange = !isSizeChange
                if (isSizeChange) {
                    txtSize.text = "A-"
                    webInfo.settings.textZoom = 120
                } else {
                    txtSize.text = "A+"
                    webInfo.settings.textZoom = 100
                }
            }
        }
    }

    /**
     * 获取文章
     */
    private fun getArticle() {
        val params = mapOf(Pair("id", "" + id))
        val service = BaseRetrofit().createService(ServerApi::class.java)
        LogUtil.w(TAG, "PARAMS=" + params.toString())
        val server: Observable<Result>
        server = if (table == "article")
            service.getArtContent(params)
        else
            service.getMagzContent(params)
        server.subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .subscribe({ response ->
                    LogUtil.d(TAG, response.toString())
                    when (response.getCode()) {
                        200 -> {
                            if (table == "magazine")
                                magazine = GsonUtils.str2Bean(GsonUtils.Gson2Str(response.getData()), Magazine::class.java)
                            else
                                article = GsonUtils.str2Bean(GsonUtils.Gson2Str(response.getData()), Article::class.java)

                            handler.sendEmptyMessage(0x123)
                            return@subscribe

                        }
                    }
                    handler.sendEmptyMessage(0x124)
                }, { t ->
                    LogUtil.d(TAG, t.toString())
                    handler.sendEmptyMessage(0x124)
                })
    }

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                if (table == "magazine")
                    webInfo.loadDataWithBaseURL("", getHtml(magazine!!.artContent!!),
                            "text/html", "utr-8", null)
                else
                    webInfo.loadDataWithBaseURL("", getHtml(article!!.artContent!!),
                            "text/html", "utr-8", null)
            }
            else -> {

            }
        }
        if (refreshWeb.isRefreshing) refreshWeb.isRefreshing = false
        if (dialog.isShowing) dialog.dismiss()
        false
    })

    fun getHtml(html: String): String {
        val doc = Jsoup.parse(html)
        val ele = doc.getElementsByTag("img")
        for (item in ele) {
            item.attr("style", "max-width:100%;height:auto")
        }
        return doc.toString()
    }
}